package com.magic.cd.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 转换消息工具类
 * */
@SuppressWarnings("unchecked")
public class MessageUtils {
	
	/**
	 * 将微信接收到的XML消息转换为对象，这里的XML节点名称需要和类的字段名称一致
	 * @param   clz   需要转换的类
	 * @param	in    微信消息响应
	 * @return  T
	 * */
	public static <T> T parseXML(InputStream in,Class<T> clz){
		return MessageUtils.parseXML(MessageUtils.parseInputStream(in), clz);
	}
	
	/**
	 * 将微信接收到的XML消息转换为对象，这里的XML节点名称需要和类的字段名称一致
	 * @param   clz   需要转换的类
	 * @param	xml   符合xml格式的消息
	 * @return  T
	 * */
	public static <T> T parseXML(String xml,Class<T> clz){
		Object msg = null;
		try {
			if (xml!=null&&xml.length()>10) {
				Document document = DocumentHelper.parseText(xml);
				Element root = document.getRootElement();
				Iterator<?> it = root.elementIterator();
				msg = clz.newInstance();
				while (it.hasNext()) {
					Element ele = (Element) it.next();
					Field field = clz.getDeclaredField(ele.getName());
					field.setAccessible(true);
					field.set(msg, ele.getText());
				}
			}

		} catch (Exception e) {
			//TODO
			e.printStackTrace();
		}
		return (T) msg;
	}
	
	/**
	 * 将对象转换为微信识别的XML格式，这里的XML节点名称需要和类的字段名称一致
	 * @param   obj   待转换对象
	 * @return  String
	 * */
	public static String toXMLString(Object obj,String root){
		StringBuffer buffer = new StringBuffer("<").append(root).append(">");
		try {
			if (obj!=null) {
				Class<?> clz = obj.getClass();
				
				Method[] methods = clz.getMethods();
				for (Method me : methods) {
					String name = me.getName();
					int index = name.indexOf("get");
					Class<?>[] types = me.getParameterTypes();
					if(index!=-1&&types.length==0){
						name = name.substring(3);
						me.setAccessible(true);
						Object value = me.invoke(obj, null);
						if(value!=null){
							if(value instanceof String){
								buffer.append("<").append(name).append(">");
								buffer.append("<![CDATA[").append(value).append("]]>");
								buffer.append("</").append(name).append(">");
							}else if(value instanceof Number ||value instanceof Boolean){
								buffer.append("<").append(name).append(">");
								buffer.append(value);
								buffer.append("</").append(name).append(">");
							}else if(value instanceof Date){
								
							}else if(value instanceof Class || value instanceof Map){
								
							}else if(value instanceof List){
								List<Object> list = (List)value;
								if(list.size()>0){
									Object eh = list.get(0);
									if(!(eh instanceof Number ||eh instanceof String ||eh instanceof Date)){
										buffer.append("<").append(name).append(">");
										for (Object e : list) {
											if(e!=null){
												String str = e.getClass().getSimpleName();
												buffer.append(MessageUtils.toXMLString(e, str));
											}
										}
										buffer.append("</").append(name).append(">");
									}
								}
							}else{
								buffer.append(MessageUtils.toXMLString(value, name));
							}
						}
					}
				}
			}

		} catch (Exception e) {
			//TODO
			e.printStackTrace();
		}
		return buffer.append("</").append(root).append(">").toString();
	}
	
	/**
	 * xml格式的字符串
	 * 将请求中的数据转换为字符串
	 * @param	in	  请求
	 * @return  String
	 * */
	public static String parseInputStream(InputStream in){
		StringBuffer sb = new StringBuffer();  
		try {
			InputStreamReader reader = new InputStreamReader(in,"UTF-8");
			BufferedReader buf = new BufferedReader(reader);  
			String tp = "";  
			while((tp=buf.readLine())!=null) {  
				sb.append(tp);  
			}  
		} catch (Exception e) {
			// TODO 
		}  
        return sb.toString();   
	}
}